import logging
import sys
import random
import time
from typing import Optional, Dict, List, Any

from cozepy import COZE_CN_BASE_URL, Coze, TokenAuth,Message,MessageObjectString,exception
from cozepy.log import setup_logging
import json


def get_weighted_random_api(api_configs: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    根据权重随机选择API配置
    
    Args:
        api_configs: API配置列表，每个配置必须包含'weight'字段
        
    Returns:
        随机选择的API配置
    """
    if not api_configs:
        raise ValueError("API配置列表不能为空")
    
    # 提取所有权重值
    weights = [config.get('weight', 0) for config in api_configs]
    
    # 确保至少有一个权重大于0
    if sum(weights) <= 0:
        # 如果所有权重都是0或负数，则使用均匀分布
        return random.choice(api_configs)
    
    # 根据权重随机选择配置
    return random.choices(api_configs, weights=weights, k=1)[0]


def log_api_usage(api_config: Dict[str, Any], success: bool, response_time: float, error_msg: str = ""):
    """
    记录API使用情况，便于分析和调试
    
    Args:
        api_config: 使用的API配置
        success: 调用是否成功
        response_time: 响应时间(秒)
        error_msg: 如果失败，错误信息
    """
    try:
        log_data = {
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "bot_id": api_config.get("bot_id", "unknown"),
            "success": success,
            "response_time": response_time,
            "error": error_msg
        }
        
        # 记录到日志文件
        with open("api_usage_log.json", "a", encoding="utf-8") as f:
            f.write(json.dumps(log_data) + "\n")
    except Exception as e:
        # 记录日志失败不应影响主程序
        pass


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("请提供一个参数。")
        sys.exit(1)
    wall_type = sys.argv[1]
    quality = sys.argv[2]
    prompt = sys.argv[3]

    # print(file_path,prompt)
    # exit()
    config_mobile_api = [
        {
            "coze_api_token": "pat_iPQnrNS8ATXONipoEZCkJ3gOdd2pZD8Xf3ibS0XfkrEgDpTHgz58BoJTpB6io3yf",
            "workflow_id": "7515357817043714089",
            'weight':70,
        },
        
    ]

    config_desktop_api = [
        {
            "coze_api_token": "pat_iPQnrNS8ATXONipoEZCkJ3gOdd2pZD8Xf3ibS0XfkrEgDpTHgz58BoJTpB6io3yf",
            "workflow_id": "7515409285842321423",
            'weight':70,
        },
    ]
    # 根据权重随机选择API配置
    config_api = config_mobile_api if wall_type == "mobile" else config_desktop_api
    selected_api = get_weighted_random_api(config_api)
    coze_api_token = selected_api["coze_api_token"]
    workflow_id = selected_api["workflow_id"]
    
    # 输出选择的API信息（仅用于调试，生产环境可移除）
    # print(f"使用API配置: {bot_id}, 权重: {selected_api['weight']}")
    # exit()

    # Init the Coze client through the access_token.
    coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=COZE_CN_BASE_URL)

    # 定义要传递给工作流的参数
    workflow_inputs = {
        "input": prompt,
        "quality": quality,
    }

    # 创建工作流运行实例并传递参数
    workflow = coze.workflows.runs.create(
        workflow_id=workflow_id,
        parameters=workflow_inputs  # 传递参数给工作流
    )
    print(workflow.data)
    # log_api_usage(selected_api, success, response_time, error_msg)
